import React, { useState, useEffect } from 'react';

import { NavBar, Icon, List, InputItem, Picker, DatePicker, TextareaItem, Button, Toast, Accordion, Modal, ImagePicker } from 'antd-mobile';

import { logout as logoutOfTutor, GetTutorCheckCode as GetCheckCode, uploadPict, previewPict, postUpdatePhoto, PostTutorActionUpdate,deleteFile } from "@/api/login.js";

import { R, MAX_LENGTH_PHOTO, sexList } from "@/assets/js/dict"

import { GetTutorActionDetails, postDeleteResume } from '@/api/login.js'
import { updatePhoneOfTutor, getPhoneCodeForUpdatePhone } from "@/api/tutor/tutor";

import { createForm } from 'rc-form'

import './userInfo.scss';

const confirm = Modal.alert;
const Item = List.Item;
const Brief = Item.Brief;

var reImgObj = []; // 学生证照片 imgObj
var reId = []; // 学生证照片 id

function UpdataUserInfo (props) {
    const [userInfoDetailsObject, setUserInfoDetailsObject] = useState({}); // 个人信息
    const [userInfoDetailsObjectRule, SetUserInfoDetailsObjectRule] = useState({}); // 个人信息 错误信息
    const [pict, setPict] = useState([]); // 学生证照片
    const [photo, setPhoto] = useState([]); // 头像照片

    const [imgObject, SetImgObject] = useState({});
    const { getFieldProps } = props.form;
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    let [hidden, setShow] = useState(false);


    /**
     * 压缩图片
     *@param img 被压缩的img对象
     * @param type 压缩后转换的文件类型
     * @param mx 触发压缩的图片最大宽度限制
     * @param mh 触发压缩的图片最大高度限制
     */
    function compressImg (img, type, mx, mh) {
        return new Promise((resolve, reject) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const { width: originWidth, height: originHeight } = img;
            // 最大尺寸限制
            const maxWidth = mx;
            const maxHeight = mh;
            // 目标尺寸
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > 1) {
                    // 宽图片
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                } else {
                    // 高图片
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                }
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片绘制
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(function (blob) {
                resolve(blob)
            }, type || 'image/png')
        })
    }

    // 压缩前将file转换成img对象
    function readImg (file) {
        return new Promise((resolve, reject) => {
            const img = new Image()
            const reader = new FileReader()
            reader.onload = function (e) {
                img.src = e.target.result
            }
            reader.onerror = function (e) {
                reject(e)
            }
            reader.readAsDataURL(file)
            img.onload = function () {
                resolve(img)
            }
            img.onerror = function (e) {
                reject(e)
            }
        })
    }

    const compress = async function (file, type, mx = 1000, mh = 1000) {
        const img = await readImg(file);
        let blob = await compressImg(img, file.type, mx, mh);
        return blob;
    };

    let onChange = async function (files, type, index) {
        console.log(files, type, index);
        if (type === "add") {
            if (files.length > 0) {
                let f = files[files.length - 1].file;
                if (f.size >= 2097152 * 2) {
                    Toast.info("请选择小于4兆的图片");
                    setPict([]);
                } else {
                    try {
                        const blob = await compress(f, f.type, 1000, 1000);
                        console.log("b----------->", blob);
                        f = blob;
                    } catch (e) {
                        console.error("error 压缩图片异常---> ", e);
                    }
                    uploadPict({ file: f, note: "学生证照片" }, (res) => {
                        if (res[R.code] === R.success) {
                            reImgObj.push({ file_id: res[R.data], url: previewPict(res[R.data]) });
                            reId.push(res[R.data])
                            setPict([...reImgObj]);
                        }
                    });
                }
            }
        } else if(type === "remove"){
            deleteFile({
                id: pict[index].file_id
            }).then(res=>{
                if(res.code === '000000'){
                    reImgObj.splice(index,1)
                    reId.splice(index,1)
                    setPict([...files]);
                }
            })
        } else{
            setPict([]);
            reImgObj = []; // 学生证照片 imgObj
            reId = []; // 学生证照片 id
        }
    }

    // 上传头像
    let onChangePhoto = async function (files, type, code) {
        console.log(files, type, code);
        if (type === "add") {
            if (files.length > 0) {
                let f = files[0].file;
                if (f.size >= MAX_LENGTH_PHOTO) {
                    Toast.info("请选择小于6兆的图片");
                    setPhoto([]);
                } else {
                    try {
                        const blob = await compress(f, f.type, 1000, 1000);
                        console.log("b----------->", blob);
                        f = blob;
                    } catch (e) {
                        console.error("error 压缩图片异常---> ", e);
                    }
                    uploadPict({ file: f, note: "用户头像" }, (res) => {
                        if (res[R.code] === R.success) {
                            let rePhoto = [{ file_id: res[R.data], url: previewPict(res[R.data]) }];
                            console.log("re---> ", rePhoto);
                            setPhoto(rePhoto);
                        }
                    });
                }
            }
        } else if(type === "remove"){
            deleteFile({
                id: photo[0].file_id
            }).then(res=>{
                if(res.code === '000000'){
                    setPhoto([...files]);
                }
            })
        } else{
            setPhoto([]);
        }
    }


    // 编辑个人信息保存
    function handleUpdataUserInfo () {
        let postData = {};
        postData = props.form.getFieldsValue().userInfoDetailsObject;
        postData.gender = postData.gender[0]
        console.log(postData)

        if (pict.length === 0) {
            Toast.info("检测到学生证照片未上传图片，请完善个人信息");
            return;
        } else if (pict.length < 2) {
            Toast.info("检测到学生证照片未上传完整，请完善个人信息");
            return;
        } else {
            postData.pict = reId.join(',');
        }

        if (photo.length === 0) {
            Toast.info("检测到头像未上传图片，请完善个人信息");
            return;
        } else {
            postData.photo = photo[0].file_id;
        }
        console.log('userInfoDetailsObject -------->>>', userInfoDetailsObject)


        postData.id = userInfoDetailsObject.id;

        console.log('postData -------->>>', postData)


        PostTutorActionUpdate(postData).then(res => {
            if (res.code == '000000') {
                Toast.success('个人信息修改成功', 1, () => {
                    props.history.goBack();
                });
            }
        }).catch(err => {

        })
    }

    useEffect(() => {
        // 查看家教详细信息 GET 
        let postData = {};
        postData.tutor_id = JSON.parse(sessionStorage.getItem('userInfo')).id;  // 孩子ID 

        GetTutorActionDetails(postData).then(res => {
            if (res.code == '000000') {
                console.log('res -------->>>', res);
                setUserInfoDetailsObject(res.responseData)
                if (res.responseData.pict) {
                    let imgFileObj = [];
                    res.responseData.pict.split(',').map(item => {
                        imgFileObj.push({
                            file_id: item,
                            url: previewPict(item)
                        })
                    })

                    reImgObj = imgFileObj;
                    reId = (res[R.data].pict).split(',')
                    setPict(imgFileObj);
                }
                if (res.responseData.photo) {
                    let imgFileObj = [];
                    res.responseData.photo.split(',').map(item => {
                        imgFileObj.push({
                            file_id: item,
                            url: previewPict(item)
                        })
                    })
                    setPhoto(imgFileObj);
                }

            }
        }).catch(err => {

        })
    }, [])

    return (
        <div className="user-info">
            <div className="page-title  student-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={() => {
                        props.history.goBack()
                    }}
                >
                    编辑个人信息
                </NavBar>

            </div>
            <div className="page-content student-content">
                <div className="student-content-piece">
                    <div className="form-box">
                        <div className="form-tit">
                            <i className="mini-block"></i>
                            <strong>基本信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item extra={userInfoDetailsObject.name}>姓名</List.Item>

                                <Picker
                                    data={sexList}
                                    cols={1}
                                    error={userInfoDetailsObjectRule.gender}
                                    onErrorClick={() => {
                                        Modal.alert(userInfoDetailsObjectRule.gender)
                                    }}
                                    {...getFieldProps('userInfoDetailsObject.gender', {
                                        initialValue: [userInfoDetailsObject.gender]
                                    })}

                                >
                                    <List.Item arrow="horizontal">性別</List.Item>
                                </Picker>
                            </List>
                        </div>

                        <div className="form-tit">
                            <i className="mini-block"></i>
                            <strong>教育信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <TextareaItem
                                    {...getFieldProps('userInfoDetailsObject.school', {
                                        initialValue: userInfoDetailsObject.school
                                    })}
                                    clear
                                    placeholder="请输入学校"
                                    error={userInfoDetailsObjectRule.school}
                                    onErrorClick={() => {
                                        Modal.alert(userInfoDetailsObjectRule.school)
                                    }}
                                    title="学校"
                                />

                                <TextareaItem
                                    {...getFieldProps('userInfoDetailsObject.code', {
                                        initialValue: userInfoDetailsObject.code
                                    })}
                                    clear
                                    placeholder="请输入学号"
                                    error={userInfoDetailsObjectRule.code}
                                    onErrorClick={() => {
                                        Modal.alert(userInfoDetailsObjectRule.code)
                                    }}
                                    title="学号"
                                />

                                <Item multipleLine >
                                    学生证照片（内容包括封面和信息页）
                                    <Brief>
                                        <ImagePicker
                                            files={pict}
                                            onChange={onChange}
                                            onImageClick={(index, fs) => console.log(index, fs)}
                                            selectable={pict.length < 2}
                                            multiple={false}
                                            accept="image/jpeg,image/jpg,image/png"
                                        />
                                    </Brief>
                                </Item>

                                <Item multipleLine  >
                                    头像（真人头像有利于家长的信赖）
                                    <Brief>
                                        <ImagePicker
                                            files={photo}
                                            onChange={onChangePhoto}
                                            onImageClick={(index, fs) => console.log(index, fs)}
                                            selectable={photo.length < 1}
                                            multiple={false}
                                            accept="image/jpeg,image/jpg,image/png"
                                        />
                                    </Brief>
                                </Item>
                            </List>
                        </div>

                        <div className="btns" style={{ margin: 0 }}>
                            <Button type="primary" onClick={handleUpdataUserInfo}>保存修改</Button>
                        </div>
                    </div>
                </div>
            </div>

        </div >
    );
}


UpdataUserInfo = createForm()(UpdataUserInfo);

export default UpdataUserInfo;